<script>
import { api } from '@/api';
import { Button, Field, Form, Toast, Uploader } from 'vant';

export default {
  components: {
    Form,
    Field,
    Button,
    Uploader
},
  computed: {
  },
  data() {
    return {
      title: '',
      content: '',
      fileUrl: '',
      uploader: []
    }
  },
  methods: {
    async handleUpload({ file }) {
      const { code, url, msg } = await api.upload(file)
      if (code === 1) {
        this.fileUrl = url
      } else {
        this.uploader = []
        this.fileUrl = ''
        Toast.fail({ message: msg ?? '上传失败' })
      }
    },
    async handleSubmit() {
      const { success, msg } = await api.space.publish({ file_url: this.fileUrl, article_content: this.content, title: this.title })
      if (success) {
        this.title = this.content = ''
        this.uploader = []
        Toast.success({ message: '发布成功' })
      } else {
        Toast.fail({ message: msg ?? '发布失败' })
      }
    }
  },
}
</script>

<template>
  <div class="space-publish">
    <Form @submit="handleSubmit">
      <Field
        v-model="title"
        name="标题"
        label="标题"
        placeholder="标题"
        :rules="[{ required: true, message: '请填写标题' }]"
      />
      <Field
        v-model="content"
        rows="2"
        autosize
        label="内容"
        type="textarea"
        maxlength="100"
        placeholder="请输入内容"
        show-word-limit
        :rules="[{ required: true, message: '请填写内容' }]"
      />
      <Field name="uploader" label="图片">
        <template #input>
          <Uploader v-model="uploader" accept="image/png, image/jpeg, image/gif" :max-count="1" :after-read="handleUpload" />
        </template>
      </Field>
      <div style="margin: 16px;">
        <Button round block type="primary" native-type="submit">发布</Button>
      </div>
    </Form>

  </div>
</template>
